<template>
  <modal :visible="visible" :model="initRecord" :title="addOrEdit===0?'新增':'修改'" okText="保存" :width="1200" @cancelHandler="onClose" @okHandler="handleSubmit">
    <template slot="content">
      <a-spin :spinning="loading" :delay="200" tip="提交中...">
        <a-form :form="form">
          <a-form-item label="字典名称" v-bind="formItemLayout">
            <a-input
              placeholder="请输入字典名称"
              v-decorator="[
                'dictName',
                { rules: [{ required: true, message: '字典名称不能为空' }], initialValue: initRecord.dictName }
              ]"
            />
          </a-form-item>
          <a-form-item label="字典类型" v-bind="formItemLayout">
            <a-input
              placeholder="请输入字典类型"
              v-decorator="[
                'dictType',
                { rules: [{ required: true, message: '字典类型不能为空' }], initialValue: initRecord.dictType }
              ]"
            />
          </a-form-item>
          <a-form-item label="字典数据" v-bind="formItemLayout">
            <a-button type="primary" @click="handleAdd()">新增一行</a-button>
          </a-form-item>
          <a-form-item label="字典数据" v-bind="formItemLayout">
            <a-table
              :dataSource="initRecord.dictDataList"
              :columns="columns"
              :pagination="false"
              :scroll="{ x: 500 }">

              <template slot="dictLabel" slot-scope="text,data">
                <a-input placeholder="请输入字典标签"  v-model="data.dictLabel"/>
              </template>
              <template slot="dictValue" slot-scope="text,data">
                <a-input placeholder="请输入字典键值" v-model="data.dictValue"/>
              </template>
              <template slot="remark" slot-scope="text,data">
                <a-textarea :rows="1" aria-placeholder="请输入备注"  v-model="data.remark"/>
              </template>
              <template slot="operation" slot-scope="scope,data,index">
                <a-button type="link" @click="handleDelete(data.dictCode,index)" class="icon">删除</a-button>
              </template>
            </a-table>
          </a-form-item>

          <a-form-item label="状态" v-bind="formItemLayout">
            <a-select
              :showArrow="true"
              v-decorator="['status', { rules: [{ required: true, message: '请选择' }], initialValue: initRecord.status }]"

              placeholder="请选择"
              :options="[
                  { key: 0, value: 0, title: '正常' },
                  { key: 1, value: 1, title: '停用' }
                ]"
            >
            </a-select>
          </a-form-item>

          <a-form-item label="备注" v-bind="formItemLayout">
            <a-textarea :rows="4"  placeholder="请输入备注"  v-decorator="['remark', { rules: [], initialValue: initRecord.remark }]"/>
          </a-form-item>

        </a-form>
      </a-spin>
    </template>
  </modal>
</template>
<script>
import modal from '~/tool/modal';
import RichEditor from '@/components/editor/RichEditor';
import {fileOperationWithRenderImageData} from '@/mixin/image-operation';
import {regexp} from 'utils/common';
import columns from './dataColunms';

const formItemLayout = {
  labelCol: {span: 4},
  wrapperCol: {span: 19}
};


export default {
  name: 'add',
  components: {
    modal,
    RichEditor
  },
  mixins: [fileOperationWithRenderImageData],
  props: {
    // 新增：0，编辑：1
    addOrEdit: {
      type: Number,
      default: 0
    },
    initRecord: {
      type: Object,
      default: () => ({})
    },
    visible: {
      default: false
    },
    // 新增记录
    apiURL: {
      type: Object,
      default: () => ({})
    },
    // 字典数据
    dictDataList: {
      type: Array,
      value: []
    },
  },
  data() {
    return {
      regexp,
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      // 需要提交的数据
      submitData: {},
      columns,  // 表头字段
      // tags: [],
      // pickedTags: [],
      content: '',
      isShowAddSpecificationBtn: true,
      specList: [],  // 界面上显示的spec
      delCodes: [],  // 删除字典数据的dictCode
      specItems: [], // 有效的spec
      specSKUColumns: [],
      specSKUItems: [],  // sku数组
      specObj: {}, // 结果对象
      specArr: [], // 结果数组
      specNum: 0, // 判断是在第几层，用作keys的index
      specKeys: [],
    };
  },
  methods: {
    // 重置
    reset() {
      this.loading = false
      this.content = ''
      this.pickedTags = []
      this.form.resetFields()
    },
    handleDelete(dictCode,index) {
      if (dictCode){
        if (dictCode){
          this.delCodes.push(dictCode)
        }
      }
      this.initRecord.dictDataList.splice(index, 1);
    },
    handleAdd() {
      let temp = JSON.parse(JSON.stringify(this.initRecord.dictDataList))
      let list = {}
      this.$set(list,'dictCode',undefined)
      this.$set(list,'dictSort',undefined)
      this.$set(list,'dictLabel',undefined)
      this.$set(list,'dictValue',undefined)
      this.$set(list,'dictType',undefined)
      this.$set(list,'isDefault',undefined)
      this.$set(list,'status',undefined)
      this.$set(list,'remark',undefined)
      temp.push(list)
      this.$set(this.initRecord,'dictDataList',temp)
    },
    // 关闭弹窗
    onClose() {
      // this.$confirm({
      //   title: '确定放弃编辑吗？',
      //   content: '',
      //   okText: '确定',
      //   cancelText: '取消',
      //   onOk: this.onCloseConfirm
      // });
      this.onCloseConfirm();
    },
    // 确定关闭弹窗
    onCloseConfirm() {
      // this.visible=false;
      this.reset();
      this.$emit('close');
    },
    // 新增提交
    handleSubmit() {
      let that = this;
      let tmpObj = that.form.getFieldsValue();
      let validateFieldArr = ["dictName","dictType","status","remark"];
      that.form.validateFields(validateFieldArr, (err, values) => {
        if (!err) {
          for (let  i = 0 ; i <this.initRecord.dictDataList.length;i++){
            let data = this.initRecord.dictDataList[i];
            if (!data.dictLabel){
              that.$message.warning('请输入第'+(i+1)+'行的字典标签');
              return;
            }
            if (!data.dictValue){
              that.$message.warning('请输入第'+(i+1)+'行的字典键值');
              return;
            }
          }
          this.$set(this.initRecord,'dictName',values.dictName)
          this.$set(this.initRecord,'dictType',values.dictType)
          this.$set(this.initRecord,'status',values.status)
          this.$set(this.initRecord,'remark',values.remark)
          this.initRecord.dataList=JSON.parse(JSON.stringify(this.initRecord.dictDataList))
          this.initRecord.delCodes=JSON.parse(JSON.stringify(this.delCodes))
          if (this.addOrEdit === 0) {
            that.$post(that.apiURL.addRecords,  this.initRecord,2).then(r => {
              that.$message.success("新增成功")
              this.onCloseConfirm();
            }).catch(r => {
              that.loading = false;
            });
          } else {
            that.$post(that.apiURL.editRecords, this.initRecord,2).then(r => {
              that.$message.success("修改成功")
              this.onCloseConfirm();
            }).catch(r => {
              that.loading = false;
            });
          }
        }
      });
    },
    // 确定新增提交
    handleConfirmSubmit() {
    }
  },
  mounted() {

  },
};
</script>
